<?php
/*------------------------------------------------------------------------
 # SM Shop By - Version 1.0
 # Copyright (c) 2014 YouTech Company. All Rights Reserved.
 # @license - Copyrighted Commercial Software
 # Author: YouTech Company
 # Websites: http://www.magentech.com
-------------------------------------------------------------------------*/?>

<?php
    $_productCollection=$this->getLoadedProductCollection();
    $_helper = $this->helper('catalog/output');
?>
<?php if(!$_productCollection->count()): ?>
<p class="note-msg"><?php echo $this->__('There are no products matching the selection.') ?></p>
<?php else: ?>
<?php if (!$this->getRequest()->isAjax()): ?>
<div id="ajax-errors" style="display: none;">
    <ul class="messages">
        <li class="error-msg">
            <ul>
                <li><span><?php echo $this->__('An error occurred, please try again later.'); ?></span></li>
            </ul>
        </li>
    </ul>
</div>
<div id="loading" style="display: none; margin-bottom: 10px; text-align: center;">
    <img class="v-middle" alt="" src="<?php echo $this->getSkinUrl('images/loader-shopby.gif'); ?>"> <?php echo $this->__('Loading, please wait...'); ?>
</div>




<?php
function getBestsellingProducts() {
//get current category id
$catID = Mage::getModel('catalog/layer')->getCurrentCategory()->getId();
$productCount = 5;
// store ID
$storeId = Mage::app()->getStore()->getId();
$category = Mage::getModel('catalog/category')->load($catID);
$best_products = Mage::getResourceModel('reports/product_collection')
->addAttributeToSelect('*')
->setStoreId($storeId)
->addStoreFilter($storeId)
->addCategoryFilter($category)
->addOrderedQty()
->setOrder('ordered_qty', 'desc')
->setPageSize($productCount);

Mage::getSingleton('catalog/product_status')->addVisibleFilterToCollection($best_products);
Mage::getSingleton('catalog/product_visibility')->addVisibleInCatalogFilterToCollection($best_products);

return $best_products;
}

$best_products = getBestsellingProducts();
?>
<?php if ($best_products->getSize() > 0): ?>
<div class="page-title">
	<h1><?php echo $this->__('Recommended Products');?></h1>
</div>
<div class="container-slider-best products-grid">
	<div class="block-content">
		<div class="page-button top style">
            <ul class="control-button">
                <li class="prev_best"><i></i>Prev</li>
                <li class="next_best"><i></i>Next</li>
            </ul>		
        </div>

		<div class="container-slider">
			<div id="box-bestseller" class="slider cols-6 preset01-3 preset01-3 preset02-2 preset03-2 preset04-1 preset05-1 js-loaded">
				<div class="vpo-wrap">
					<div class="vp">
						<div class="vpi-wrap">
						<?php
						foreach ($best_products->getItems() as $_product): 
							$id_product = Mage::getModel('catalog/product')->load($_product->getId());
							$count_input_qty++;
							$now = date("Y-m-d H:m:s");
							$newsFrom= $_product->getNewsFromDate(); //substr($_product->getData('news_from_date'),0,10);
							$newsTo= $_product->getNewsToDate();   //substr($_product->getData('news_to_date'),0,10);

							$specialprice = Mage::getModel('catalog/product')->load($_product->getId())->getSpecialPrice();
							$price = Mage::getModel('catalog/product')->load($_product->getId())->getPrice();
							$saleoff= round(($price - $specialprice)/$price*100) ;?>
							<div class="item respl-item">
								<div class="item-inner">
									<div class="w-image-box">
										<div class="item-image">
											<?php $_media = Mage::getModel('catalog/product')->load($_product->getId())->getMediaGalleryImages() ?>			
											<?php $count_item=0; $check_img=0;?>		
											<?php $check_img = count($_media);?>				
												<a class="<?php if ($check_img >= 2) echo $this->__('rspl-image');?>" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>">
													<!--SHOW 2 IMAGE FOR PRODUCTS-->
														<?php if ($check_img >= 2): ?>
															<?php foreach($_media as $_img): ?>
																	<?php $count_item++;?>
																	<img class="<?php if($count_item==1) echo $this->__('first_image')?> <?php if($count_item==2) echo $this->__('last_image')?>" src="<?php echo $this->helper('catalog/image')->init($_product, 'image', $_img->getFile())->constrainOnly(true)->keepAspectRatio(true)->keepFrame(false)->resize(270,270); ?>" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true); ?>" />
																	<?php if($count_item==2) break;?>
															<?php endforeach; ?>
														<?php else: ?>
															<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepAspectRatio(false)->resize(270,270); ?>" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
														<?php endif?>				
													<!--END SHOW 2 IMAGE FOR PRODUCTS-->
												</a>
												
												
										</div>	
											<?php if ($newsFrom !="" && $now>=$newsFrom && ($now<=$newsTo || $newsTo=="")){?>
												<div class="new-product">
													<?php echo $this->__('New'); ?>
												</div>
											<?php }?>
											<?php if (($specialprice && ($special_from_date <= $now) && ($special_to_date >= $now || $special_to_date =="" ))){
												//echo "<span class='saleoff-grid'>sale off</span>"; ?>
												<div class='sale-item'>
													<?php echo $this->__('Sale'); ?>
												</div>
											<?php }?>	
									</div>
								
								<div class="item-info">
									<div class="item-title ">
										<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->htmlEscape($_product->getName()) ?>">
											<?php echo $this->htmlEscape($_product->getName()) ?>
										</a>
									</div>
									<div class="item-review">
										<?php  echo $this->getReviewsSummaryHtml($_product, "short", true); ?>
									</div>
									
									<div class="item-price">
										<?php //echo $this->getPriceHtml($_product, false, '_blb') ?>
										<?php echo $this->getPriceHtml($_product, true) ?>
									</div>
									
									<div class="item-addto-wrap">
										<div class="button-action item-addcart">
											<?php if($_product->isSaleable()): ?>
											<a class="button btn-cart" title="<?php echo $this->__('Add to Cart') ?>" href="javascript:void(0);" onclick="setLocation('<?php echo $this->getAddToCartUrl($id_product) ?>')">
												<?php echo $this->__('Add to Cart') ?>
											</a>
											<?php else: ?>
											<p class="availability out-of-stock">
												<span><?php echo $this->__('Out of stock') ?> </span>
											</p>
											<?php endif; ?>	
										</div>
										<?php if( $_compareUrl=$this->getAddToCompareUrl($_product) ): ?>
											<a class="link-compare" href="<?php echo $_compareUrl ?>" title="<?php echo $this->__('Add to Compare'); ?>">
												<?php echo $this->__('Add to Compare') ?>
											</a>
										<?php endif;?>
										<?php if ( $this->helper('wishlist')->isAllow() ) : ?>
											<a class="link-wishlist" href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" title="<?php echo $this->__('Add to Wishlist') ?>">
												<?php echo $this->__('Add to Wishlist') ?>
											</a>
										<?php endif; ?>
									</div>	
								</div>
								</div>	
							</div>
						<?php endforeach; ?>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
</div>


<script>
	$jsmart(document).ready(function($){
        $('#box-bestseller').responsiver({
            interval: 0,
			speed: 300,
			start: 0,
			step: 1,
			circular: true,
			preload: true,
			fx: 'slide',
			pause: 'hover',
			control:{
			prev: '.control-button li[class="prev_best"]',
			next: '.control-button li[class="next_best"]'
			},
			getColumns: function(element){
			var match = $(element).attr('class').match(/cols-(\d+)/);
			if (match[1]){
			var column = parseInt(match[1]);
			} else {
			var column = 1;
			}
			if (!column) column = 1;
			return column;
			}
        });
    });
</script>
<?php
endif;
?>



<script>
	jQuery(document).ready(function($){
		var str_title = $(".title-r").text();
		//alert(str_title);
		$(".title-rewite > h1").html(str_title);
	});
</script>
<div class="page-title title-rewite">
	<h1></h1>
</div>
<div id="catalog-listing">
<?php endif; ?>
    <div class="category-products">
		<div class="toolbar-top">
        <?php echo $this->getToolbarHtml() ?>
		</div>
        <?php // List mode ?>
        <?php if($this->getMode()!='grid'): ?>
        <?php $_iterator = 0; ?>
        <ol class="products-list" id="products-list">
        <?php foreach ($_productCollection as $_product): 
			$id_product = Mage::getModel('catalog/product')->load($_product->getId());
			$count_input_qty++;
			$now = date("Y-m-d H:m:s");
			$newsFrom= $_product->getNewsFromDate(); //substr($_product->getData('news_from_date'),0,10);
			$newsTo= $_product->getNewsToDate();   //substr($_product->getData('news_to_date'),0,10);
			
			$specialprice = Mage::getModel('catalog/product')->load($_product->getId())->getSpecialPrice();
			$price = Mage::getModel('catalog/product')->load($_product->getId())->getPrice();
			$saleoff= round(($price - $specialprice)/$price*100) ;
		?>
            <li class="item <?php if( ++$_iterator == sizeof($_productCollection) ): ?> last<?php endif; ?>">
				<div class="item-inner">
					<div class="w-image-box">
						<div class="product-image">
							<?php $_media = Mage::getModel('catalog/product')->load($_product->getId())->getMediaGalleryImages() ?>			
							<?php $count_item=0; $check_img=0;?>		
							<?php $check_img = count($_media);?>
										
							<a class="<?php if ($check_img >= 2) echo $this->__('rspl-image');?>" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>">
								<!--SHOW 2 IMAGE FOR PRODUCTS-->
									<?php if ($check_img >= 2): ?>
										<?php foreach($_media as $_img): ?>
												<?php $count_item++;?>
												<img class="<?php if($count_item==1) echo $this->__('first_image')?> <?php if($count_item==2) echo $this->__('last_image')?>" src="<?php echo $this->helper('catalog/image')->init($_product, 'image', $_img->getFile())->constrainOnly(true)->keepAspectRatio(true)->keepFrame(false)->resize(270,270); ?>" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true); ?>" />
												<?php if($count_item==2) break;?>
										<?php endforeach; ?>
									<?php else: ?>
										<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepAspectRatio(false)->resize(270,270); ?>" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
									<?php endif?>
									
								<!--END SHOW 2 IMAGE FOR PRODUCTS-->
							</a>
							
							
						</div>
						<?php if ($newsFrom !="" && $now>=$newsFrom && ($now<=$newsTo || $newsTo=="")){?>
							<div class="new-product">
								<div class="new-content">
									<?php echo $this->__('New'); ?>
								</div>
							</div>
						<?php }?>
						<?php if (($specialprice && ($special_from_date <= $now) && ($special_to_date >= $now || $special_to_date =="" ))){?>
							<div class='sale-item'>
								<?php echo $this->__('Sale'); ?>
							</div>
						<?php }?>	
					</div>	
					<div class="product-info">
						<div class="product-name">
							<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>">
							<?php if( strlen($_helper->productAttribute($_product, $_product->getName(), 'name')) > 100 ){
									 echo substr($_helper->productAttribute($_product, $_product->getName(), 'name'), 0, 100);
                                } else {
                                    echo $_helper->productAttribute($_product, $_product->getName(), 'name');
                                }?>
							</a>
						</div>
						
						<div class="review-product">
							<div class="item-review">
								<?php  echo $this->getReviewsSummaryHtml($_product, "short", true); ?>
							</div>
						</div>
						<!--
						<div class="product-review">
							<?php//  echo $this->getReviewsSummaryHtml($_product, false, true); ?>
						</div>		
						-->
						<div class="product-price">
							<?php //echo $this->getPriceHtml($_product, true) ?>
							<?php echo $this->getPriceHtml($_product, true) ?>
						</div>
						<?php if($_product->getshort_description()) { ?>
						<div class="product-desciption">
							<?php echo $_product->getshort_description();?>
						</div>
						<?php } ?>	
							<div class="item-addto-wrap">
								<div class="button-action item-addcart">
									<?php if($_product->isSaleable()): ?>
									<a class="button btn-cart" title="<?php echo $this->__('Add to Cart') ?>" href="javascript:void(0);" onclick="setLocation('<?php echo $this->getAddToCartUrl($id_product) ?>')">
										<?php echo $this->__('Add to Cart') ?>
									</a>
									<?php else: ?>
									<p class="availability out-of-stock">
										<span><?php echo $this->__('Out of stock') ?> </span>
									</p>
									<?php endif; ?>	
								</div>
								
								<?php if( $_compareUrl=$this->getAddToCompareUrl($_product) ): ?>
									<a class="link-compare" href="<?php echo $_compareUrl ?>" title="<?php echo $this->__('Add to Compare'); ?>">
										<?php echo $this->__('Add to Compare') ?>
									</a>
								<?php endif;?>
								
								
								<?php if ( $this->helper('wishlist')->isAllow() ) : ?>
									<a class="link-wishlist" href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" title="<?php echo $this->__('Add to Wishlist') ?>">
										<?php echo $this->__('Add to Wishlist') ?>
									</a>
								<?php endif; ?>
								
							</div>	
					</div>
					
				</div>
			</li>
        <?php endforeach; ?>
        </ol>
        <script type="text/javascript">decorateList('products-list', 'none-recursive')</script>

        <?php else: ?>

        <?php // Grid Mode ?>

        <?php $_collectionSize = $_productCollection->count() ?>
        <?php $_columnCount = $this->getColumnCount(); ?>
		<div class="products-grid">
			<div class="row">
        <?php $i=0; foreach ($_productCollection as $_product): 
			$id_product = Mage::getModel('catalog/product')->load($_product->getId());
			$now = date("Y-m-d H:m:s");
			$newsFrom= $_product->getNewsFromDate(); //substr($_product->getData('news_from_date'),0,10);
			$newsTo= $_product->getNewsToDate();   //substr($_product->getData('news_to_date'),0,10);
			$specialprice = Mage::getModel('catalog/product')->load($_product->getId())->getSpecialPrice();
			$price = Mage::getModel('catalog/product')->load($_product->getId())->getPrice();
			$saleoff= round(($price - $specialprice)/$price*100) ;
		?>
            <?php if ($i++%$_columnCount==0): ?>
            
            <?php endif ?>
				
					<div class="item col-lg-4 col-md-4 col-sm-6 col-xs-6 respl-item">
					<div class="item-inner">
						<div class="w-image-box">	
							<div class="item-image">
								<!--SHOW 2 IMAGE FOR PRODUCTS-->
									<?php $_media = Mage::getModel('catalog/product')->load($_product->getId())->getMediaGalleryImages() ?>
									
									<?php $count_item=0; $check_img=0;?>
									
									<?php $check_img = count($_media);?>
									
								<a class="<?php if ($check_img >= 2) echo $this->__('rspl-image');?>" href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>">
									
									
									
									<?php if ($check_img >= 2): ?>
										<?php foreach($_media as $_img): ?>
												<?php $count_item++;?>
												<img class="<?php if($count_item==1) echo $this->__('first_image')?> <?php if($count_item==2) echo $this->__('last_image')?>" src="<?php echo $this->helper('catalog/image')->init($_product, 'image', $_img->getFile())->constrainOnly(true)->keepAspectRatio(true)->keepFrame(false)->resize(270,270); ?>" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true); ?>" />
												<?php if($count_item==2) break;?>
										<?php endforeach; ?>
									<?php else: ?>
										<img src="<?php echo $this->helper('catalog/image')->init($_product, 'small_image')->keepAspectRatio(false)->resize(270,270); ?>" alt="<?php echo $this->stripTags($this->getImageLabel($_product, 'small_image'), null, true) ?>" />
									<?php endif?>
									
									<!--END SHOW 2 IMAGE FOR PRODUCTS-->
									
									
								</a>
								
								
								
							</div>
							<?php if ($newsFrom !="" && $now>=$newsFrom && ($now<=$newsTo || $newsTo=="")){?>
								<div class="new-product">
										<?php echo $this->__('New'); ?>
								</div>
							<?php }?>
							<?php if (($specialprice && ($special_from_date <= $now) && ($special_to_date >= $now || $special_to_date =="" ))){?>
								<div class='sale-item'>
									<?php echo $this->__('Sale'); ?>
								</div>
							<?php }?>	
						</div>
						<div class="item-info">
							<div class="item-title ">
								<a href="<?php echo $_product->getProductUrl() ?>" title="<?php echo $this->stripTags($_product->getName(), null, true) ?>">
								<?php if( strlen($_helper->productAttribute($_product, $_product->getName(), 'name')) > 100 ){
									 echo substr($_helper->productAttribute($_product, $_product->getName(), 'name'), 0, 100);
                                } else {
                                    echo $_helper->productAttribute($_product, $_product->getName(), 'name');
                                }?>
								</a>
							</div>
							<div class="item-review">
								<?php  echo $this->getReviewsSummaryHtml($_product, "short", true); ?>
							</div>
							
							<div class="item-price">
								<?php // echo $this->getPriceHtml($_product, true) ?>
								<?php echo $this->getPriceHtml($_product, true) ?>
							</div>
							<!--
							<div class="item-desc">
								<?php 
									echo substr($_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description'), 0, 70);
								?>
							</div>
							-->
							<div class="item-addto-wrap">
								<div class="button-action item-addcart">
									<?php if($_product->isSaleable()): ?>
									<a class="button btn-cart" title="<?php echo $this->__('Add to Cart') ?>" href="javascript:void(0);" onclick="setLocation('<?php echo $this->getAddToCartUrl($id_product) ?>')">
										<?php echo $this->__('Add to Cart') ?>
									</a>
									<?php else: ?>
									<p class="availability out-of-stock">
										<span><?php echo $this->__('Out of stock') ?> </span>
									</p>
									<?php endif; ?>	

									<?php if( $_compareUrl=$this->getAddToCompareUrl($_product) ): ?>
										<a class="link-compare" href="<?php echo $_compareUrl ?>" title="<?php echo $this->__('Add to Compare'); ?>">
											<?php echo $this->__('Add to Compare') ?>
										</a>
									<?php endif;?>
									
									<?php if ( $this->helper('wishlist')->isAllow() ) : ?>
										<a class="link-wishlist" href="<?php echo $this->helper('wishlist')->getAddUrl($_product) ?>" title="<?php echo $this->__('Add to Wishlist') ?>">
											<?php echo $this->__('Add to Wishlist') ?>
										</a>
									<?php endif; ?>
									
																	
								</div>
							</div>				
						</div>
						
					</div>
				
				</div>
            <?php if ($i%$_columnCount==0 || $i==$_collectionSize): ?>
				
            <?php endif ?>
            <?php endforeach ?>
			</div>
		</div>
            <script type="text/javascript">decorateGeneric($$('ul.products-grid'), ['odd','even','first','last'])</script>
        <?php endif; ?>

        <div class="toolbar-bottom">
            <?php echo $this->getToolbarHtml() ?>
        </div>
    </div>
<?php if (!$this->getRequest()->isAjax()): ?>
</div>
<?php endif; ?>
<?php endif; ?>

<?php if ($this->helper('sm_shopby')->isAjaxEnabled() && !$this->getRequest()->isAjax()): ?>
<script type="text/javascript">
    //<![CDATA[
    function pushState(data, link, replace) {
        var History = window.History;
        if ( !History.enabled ) {
            return false;
        }

        if (replace) {
            History.replaceState(data, document.title, link);
        } else {
            History.pushState(data, document.title, link);
        }
    }
    
    function handleEvent(el, event) {
        var url, fullUrl;
        if (typeof el === 'string') {
            url = el;
        } else if (el.tagName.toLowerCase() === 'a') {
            url = $(el).readAttribute('href');
        } else if (el.tagName.toLowerCase() === 'select') {
            url = $(el).getValue();
        }

        <?php // Add this to query string for full page caching systems ?>
        if (url.indexOf('?') != -1) {
            fullUrl = url + '&isLayerAjax=1';
        } else {
            fullUrl = url + '?isLayerAjax=1';
        }
        
        $('loading').show();
        $('ajax-errors').hide();
        
        pushState(null, url, false);
        
        new Ajax.Request(fullUrl, {
            method: 'get',
            onSuccess: function(transport) {
                if (transport.responseJSON) {                    
                    $('catalog-listing').update(transport.responseJSON.listing);
                    $('layered-navigation').update(transport.responseJSON.layer);
                    pushState({
                        listing: transport.responseJSON.listing,
                        layer: transport.responseJSON.layer
                    }, url, true);
                    ajaxListener();
                } else {
                    $('ajax-errors').show();
                }
                $('loading').hide();
            }
        });
        
        if (event) {
            event.preventDefault();
        }
    }
    function ajaxListener() {
        var els;
        els = $$('div.pager a').concat(
            $$('div.sorter a'),
            $$('div.pager select'),
            $$('div.sorter select'),
            $$('div.block-layered-nav a')
        );
        els.each(function(el) {
            if (el.tagName.toLowerCase() === 'a') {
                $(el).observe('click', function(event) {
                    handleEvent(this, event);
                });
            } else if (el.tagName.toLowerCase() === 'select') {
                $(el).setAttribute('onchange', '');
                $(el).observe('change', function(event) {
                    handleEvent(this, event);
                });
            }
        });
    }
    document.observe("dom:loaded", function() {
        ajaxListener();
        
        (function(History) {
            if ( !History.enabled ) {
                return false;
            }

            pushState({
                listing: $('catalog-listing').innerHTML,
                layer: $('layered-navigation').innerHTML
            }, document.location.href, true);

            // Bind to StateChange Event
            History.Adapter.bind(window, 'popstate', function(event) {
                if (event.type == 'popstate') {
                    var State = History.getState();
                    $('catalog-listing').update(State.data.listing);
                    $('layered-navigation').update(State.data.layer);
                    ajaxListener();
                }                
            });
        })(window.History);
    });
    //]]>
</script>
<?php endif; ?>